//
//  RisacPicker.swift
//  Risac
//
//  Created by remy on 2018/7/28.
//

@objc public protocol RisacPickerDelegate: AnyObject {
    @objc optional func pickerItemAttr(picker: RisacPicker, indexPath: IndexPath) -> NSAttributedString?
    @objc optional func pickerDidSelected(picker: RisacPicker, indexPath: IndexPath)
}

open class RisacPicker: UIView, ViewLinable {
    public struct Options {
        public var bgColor: UIColor = .clear
        public var titleBarHeight: CGFloat = 40.0
        public var titleBarTextColor: UIColor = .black
        public var rowHeight: CGFloat = 32.0
        public lazy var titleBarTextSize: CGFloat = {
            return (titleBarHeight * 0.4).rounded()
        }()
        public init() {}
    }
    private var options: Options
    public static var global: Options = Options()
    public weak var delegate: RisacPickerDelegate?
    private var layoutFlag: Bool = false
    /// 系统选择器
    public private(set) lazy var picker: UIPickerView = {
        let picker = UIPickerView(frame: self.bounds)
        picker.showsSelectionIndicator = true
        picker.dataSource = self
        picker.delegate = self
        return picker
    }()
    private var pickerSectionWidth: CGFloat = 0.0
    public var topBar: UIView? {
        didSet {
            oldValue?.removeFromSuperview()
            guard let topBar = topBar else { return }
            self.insertSubview(topBar, at: 0)
            self.triggerLayout()
        }
    }
    private lazy var titleBar = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.width, height: options.titleBarHeight))
    public var titles: [String]? {
        didSet {
            if let titles = titles, titles.count > 0 {
                self.insertSubview(titleBar, at: 0)
                titleBar.removeAllSubviews()
                let titleWidth = (self.width / CGFloat(titles.count)).rounded()
                for (index, text) in titles.enumerated() {
                    let label = UILabel(frame: CGRect(x: titleWidth * CGFloat(index), y: 0.0, width: titleWidth, height: options.titleBarHeight), text: text, textColor: options.titleBarTextColor, fontSize: options.titleBarTextSize)
                    label.textAlignment = .center
                    titleBar.addSubview(label)
                }
            } else {
                titleBar.removeFromSuperview()
            }
            triggerLayout()
        }
    }
    // 数据
    public var dataList: [[String]] = [] {
        didSet {
            pickerSectionWidth = (self.width / CGFloat(dataList.count)).rounded()
        }
    }
    
    public init(frame: CGRect, _ closure: ((inout Options) -> Void)? = nil) {
        var options = RisacPicker.global
        closure?(&options)
        self.options = options
        super.init(frame: frame)
        self.backgroundColor = options.bgColor
        self.addSubview(picker)
        triggerLayout()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func selectRow(_ row: Int, inComponent component: Int = 0) {
        guard 0..<picker.numberOfComponents ~= component else { return }
        guard let arr = dataList[safe: component], arr.indices ~= row else { return }
        picker.selectRow(row, inComponent: component, animated: false)
    }
    
    public func selectedRow(inComponent component: Int = 0) -> Int? {
        guard 0..<picker.numberOfComponents ~= component else { return nil }
        return picker.selectedRow(inComponent: component)
    }
    
    public func selectedValue(inComponent component: Int = 0) -> String? {
        guard let row = self.selectedRow(inComponent: component) else { return nil }
        return dataList[safe: component]?[safe: row] ?? ""
    }
    
    public func reload(inComponent component: Int? = nil) {
        if let component = component {
            guard 0..<picker.numberOfComponents ~= component else { return }
            picker.reloadComponent(component)
        } else {
            picker.reloadAllComponents()
        }
    }
    
    public func triggerLayout() {
        self.layoutFlag = true
        self.setNeedsLayout()
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        guard layoutFlag else { return }
        layoutFlag = false
        var topSpace: CGFloat = 0.0
        if let topBar = topBar { topSpace = topBar.bottom }
        if let titles = titles, titles.count > 0 {
            titleBar.top = topSpace
            topSpace = titleBar.bottom
        }
        picker.top = topSpace
        picker.height = self.height - topSpace
    }
}

extension RisacPicker: UIPickerViewDataSource {
    public func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return dataList.count
    }
    
    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return dataList[component].count
    }
}

extension RisacPicker: UIPickerViewDelegate {
    public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return pickerSectionWidth
    }
    
    public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return options.rowHeight
    }
    
    public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return dataList[component][row]
    }
    
    public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        delegate?.pickerItemAttr?(picker: self, indexPath: IndexPath(row: row, section: component))
    }
    
    public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        delegate?.pickerDidSelected?(picker: self, indexPath: IndexPath(row: row, section: component))
    }
}
